// CryptoJS包装器，确保正确加载
// @ts-ignore
import '../utils/crypto-js.js';

// 声明全局类型
declare global {
  var global: any;
}

// 获取CryptoJS实例的简化版本
function getCryptoJSInstance(): any {
  // 按优先级检查各种全局对象
  if (typeof globalThis !== 'undefined' && (globalThis as any).CryptoJS) {
    return (globalThis as any).CryptoJS;
  }
  
  if (typeof window !== 'undefined' && (window as any).CryptoJS) {
    return (window as any).CryptoJS;
  }
  
  if (typeof global !== 'undefined' && (global as any).CryptoJS) {
    return (global as any).CryptoJS;
  }
  
  // 如果都没有找到，抛出错误
  throw new Error('CryptoJS未加载，请检查crypto-js.js是否正确导入');
}

// 获取CryptoJS实例
let cryptoJSInstance: any = null;

export async function getCryptoJS(): Promise<any> {
  if (cryptoJSInstance) {
    return cryptoJSInstance;
  }
  
  try {
    cryptoJSInstance = getCryptoJSInstance();
    return cryptoJSInstance;
  } catch (error) {
    console.error('CryptoJS加载失败:', error);
    throw new Error('CryptoJS库加载失败，请检查crypto-js.js是否正确导入');
  }
}

// 同步获取CryptoJS
export function getCryptoJSSync(): any {
  if (cryptoJSInstance) {
    return cryptoJSInstance;
  }
  
  try {
    cryptoJSInstance = getCryptoJSInstance();
    return cryptoJSInstance;
  } catch (error) {
    console.error('CryptoJS同步获取失败:', error);
    throw error;
  }
}

// MD5加密函数
export async function md5Encrypt(text: string): Promise<string> {
  const CryptoJS = await getCryptoJS();
  return CryptoJS.MD5(text).toString();
}

// 同步MD5加密函数
export function md5EncryptSync(text: string): string {
  const CryptoJS = getCryptoJSSync();
  return CryptoJS.MD5(text).toString();
}
